import traceback
from models.hotspot import Hotspot
from extensions import db
from services.platform_crawl_manager import (
    get_platform_latest_crawl_at,
    set_platform_latest_crawl_at,
)
from services.constants import PLATFORM_CONFIG
from services.utils import prepare_hotspot_data, format_paginated_result
from crawlers.ithome import get_hot_articles_from_ithome, get_new_articles_from_ithome

def fetch_ithome_hotspot_to_db(crawl_at) -> None:
    """抓取IT之家数据并存入数据库

    Parameters:
            crawl_at: 时间戳，用于记录抓取时间

    """
    try:
        # 获取IT之家日榜数据
        daily_articles, weekly_articles, monthly_articles, hot_comment_articles = get_hot_articles_from_ithome()

        latest_articles = get_new_articles_from_ithome()

        new_daily_articles = prepare_hotspot_data(daily_articles, "IT之家", "日榜", crawl_at)

        new_weekly_articles = prepare_hotspot_data(weekly_articles, "IT之家", "周榜", crawl_at)

        new_monthly_articles = prepare_hotspot_data(monthly_articles, "IT之家", "月榜", crawl_at)
        
        new_hot_comment_articles = prepare_hotspot_data(hot_comment_articles, "IT之家", "热评榜", crawl_at)

        new_latest_articles = prepare_hotspot_data(latest_articles, "IT之家", "最新", crawl_at)

        new_articles = [*new_daily_articles, *new_weekly_articles, *new_monthly_articles,*new_latest_articles, *new_hot_comment_articles]

        # 批量插入数据到数据库
        if new_articles:
            db.session.bulk_insert_mappings(Hotspot, new_articles)
            db.session.commit()

        # 更新平台最新抓取时间
        set_platform_latest_crawl_at("IT之家", crawl_at)

        print("IT之家数据抓取并存入数据库成功")

    except Exception as e:
        db.session.rollback()
        print("IT之家日榜数据抓取并存入数据库失败:", e)
        print("详细错误信息:")
        traceback.print_exc()
        raise e

def get_daily_ithome_hotspot_from_db() -> list:
    """从数据库获取IT之家日榜数据

    Parameters:
            crawl_at: 时间戳，用于记录抓取时间

    Returns:
            IT之家日榜数据列表
    """
    try:
        # 获取最新抓取时间
        latest_crawl_at = get_platform_latest_crawl_at("IT之家")

        # 从数据库获取日榜数据
        ithome_hotspots = Hotspot.query.filter_by(
            platform=PLATFORM_CONFIG["IT之家"]["id"],
            section=PLATFORM_CONFIG["IT之家"]["sections"]["日榜"],
            crawl_at=latest_crawl_at,
        ).all()

        return ithome_hotspots

    except Exception as e:
        print("从数据库中获取IT之家日榜数据失败:", e)
        print("详细错误信息:")
        traceback.print_exc()
        raise e


def get_weekly_ithome_hotspot_from_db() -> list:
    """从数据库获取IT之家周榜数据

    Parameters:
            crawl_at: 时间戳，用于记录抓取时间

    Returns:
            IT之家周榜数据列表
    """
    try:
        # 获取最新抓取时间
        latest_crawl_at = get_platform_latest_crawl_at("IT之家")

        # 从数据库获取周榜数据
        ithome_hotspots = Hotspot.query.filter_by(
            platform=PLATFORM_CONFIG["IT之家"]["id"],
            section=PLATFORM_CONFIG["IT之家"]["sections"]["周榜"],
            crawl_at=latest_crawl_at,
        ).all()

        return ithome_hotspots

    except Exception as e:
        print("从数据库中获取IT之家周榜数据失败:", e)
        print("详细错误信息:")
        traceback.print_exc()
        raise e


def get_monthly_ithome_hotspot_from_db() -> list:
    """从数据库获取IT之家月榜数据

    Parameters:
            crawl_at: 时间戳，用于记录抓取时间

    Returns:
            IT之家月榜数据列表
    """
    try:
        # 获取最新抓取时间
        latest_crawl_at = get_platform_latest_crawl_at("IT之家")

        # 从数据库获取月榜数据
        ithome_hotspots = Hotspot.query.filter_by(
            platform=PLATFORM_CONFIG["IT之家"]["id"],
            section=PLATFORM_CONFIG["IT之家"]["sections"]["月榜"],
            crawl_at=latest_crawl_at,
        ).all()

        return ithome_hotspots

    except Exception as e:
        print("从数据库中获取IT之家月榜数据失败:", e)
        print("详细错误信息:")
        traceback.print_exc()
        raise e

def get_latest_ithome_hotspot_from_db() -> list:
    """从数据库获取IT之家最新数据

    Parameters:
      crawl_at: 时间戳，用于记录抓取时间

    Returns:
      最新数据列表
    """
    try:
        # 获取最新抓取时间
        latest_crawl_at = get_platform_latest_crawl_at("IT之家")

        # 从数据库获取新榜数据
        ithome_hotspots = Hotspot.query.filter_by(
            platform=PLATFORM_CONFIG["IT之家"]["id"],
            section=PLATFORM_CONFIG["IT之家"]["sections"]["最新"],
            crawl_at=latest_crawl_at,
        ).all()

        return ithome_hotspots

    except Exception as e:
        print("从数据库中获取IT之家最新榜数据失败:", e)
        print("详细错误信息:")
        traceback.print_exc()
        raise e
    
def get_hot_ithome_hotspot_from_db() -> list:
    """从数据库获取IT之家热评榜数据

    Parameters:
      crawl_at: 时间戳，用于记录抓取时间

    Returns:
      热评榜数据列表
    """
    try:
        # 获取最新抓取时间
        latest_crawl_at = get_platform_latest_crawl_at("IT之家")

        # 从数据库获取新榜数据
        ithome_hotspots = Hotspot.query.filter_by(
            platform=PLATFORM_CONFIG["IT之家"]["id"],
            section=PLATFORM_CONFIG["IT之家"]["sections"]["热评榜"],
            crawl_at=latest_crawl_at,
        ).all()

        return ithome_hotspots

    except Exception as e:
        print("从数据库中获取IT之家热评榜数据失败:", e)
        print("详细错误信息:")
        traceback.print_exc()
        raise e
    
def get_latest_ithome_hotspot_from_db_page(page: int, page_size: int) -> list:
    """从数据库获取IT之家最新数据

    Parameters:
        page: 页码
        page_size: 每页大小

    Returns:
        最新数据列表
        {
            "pages": 总页数,
            "page": 当前页码,
            "per_page": 每页大小,
            "items": 最新数据列表,
            "total": 总数据条数}
    """
    try:
        # 获取最新抓取时间
        latest_crawl_at = get_platform_latest_crawl_at("IT之家")

        # 从数据库获取最新数据，并根据order排序
        ithome_hotspots = Hotspot.query.filter_by(
            platform=PLATFORM_CONFIG["IT之家"]["id"],
            section=PLATFORM_CONFIG["IT之家"]["sections"]["最新"],
            crawl_at=latest_crawl_at,
        ).order_by(Hotspot.order).paginate(page=page, per_page=page_size)

        return format_paginated_result(ithome_hotspots)

    except Exception as e:
        print("从数据库中获取IT之家最新数据失败:", e)
        print("详细错误信息:")
        traceback.print_exc()
        raise e